/*
 * NES for MOTO EZX Modile Phone
 * Copyright (C) 2006 OopsWare. CHINA.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: main.cpp,v 0.10 2006/06/07 $
 */

#include <qfileinfo.h>
#include <qdir.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <znoticedlg.h>

#include "main.h"
#include "smd_player.h"

#define APP_PATH "/mmc/mmca1/.Programs/Z6Pico/"
#define APP_CONF "z6pico.cfg"

MainWidget *wgMain = 0;
ZApplication *app;
ConfigFile *AppConf;
QString RomPath("");
QString SavePath("");
QString CapturePath("");


char * HARDKEYS[] = {
    "REC",
    "VOICE",
    "VOL_UP",
    "VOL_DOWN",
    "CALL",
    "HANG",
    "OK",
    "TONE",
    "C",
    "UP",
    "DOWN",
    "LEFT",
    "RIGHT",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "0",
    "SHARP",
    "STAR"
};

QFileInfo * RomFileInfo 		= 0;


MainWidget::MainWidget(QWidget *parent, char* name)
	: ZKbMainWidget((ZHeader::HEADER_TYPE)3 , parent , name , WType_TopLevel)
{
        setMainWidgetTitle("EzxPico");

        //soft keys
        softKey = new ZSoftKey(NULL , this , this);
        softKey->setText(ZSoftKey::LEFT, "Run", (ZSoftKey::TEXT_PRIORITY)0);
        softKey->setTextForOptMenuHide("Run");
        softKey->setText(ZSoftKey::RIGHT, "Exit", (ZSoftKey::TEXT_PRIORITY)0);
        softKey->setClickedSlot(ZSoftKey::RIGHT, this, SLOT(slotQuit()));
        softKey->setClickedSlot(ZSoftKey::LEFT, this, SLOT(runEmulator()));

        //scroll panel
        zsv = new ZScrollPanel(this , NULL , 0 ,  (ZSkinService::WidgetClsID)4);

	romBox = new ZComboBox();
        QDir d(RomPath, "*.smd *.bin *.gen *.zip", QDir::Name | QDir::IgnoreCase, QDir::Files | (QDir::AccessMask & ~QDir::Writable) );
	for (unsigned int i=0; i<d.count(); i++)
		romBox->insertItem( d[i] );
//	if (romBox->count() > 0 )
//		romBox->setCurrentItem(0);
//        romBox->insertItem(QString ("Earthworm_Jim_2.bin"));

        zsv->addChild(romBox, 0, 20);
//	romList->setFrameStyle( QFrame::NoFrame );
//
        layout = getVBoxLayout();
        layout->addWidget(zsv);
        setSoftKey(softKey);
//	cp = new UTIL_CST(this, tr("Run"));
//	setCSTWidget(cp);
//	ZPressButton *wp;
//	wp = cp->getRightBtn();
//	connect(wp, SIGNAL( clicked() ), SLOT( slotQuit() ));
//	wp = cp->getMidBtn();
//	connect(wp, SIGNAL(clicked()), SLOT(runEmulator()));
//
//	QPopupMenu *pp = new QPopupMenu(this, NULL);
//	connect(pp, SIGNAL(activated(int)), SLOT(menuSelect(int)));
//	mid_about = pp->insertItem(tr("About ..."));
//	wp = cp->getLeftBtn();
//	wp->setPopup(pp);



//	romList->show();


}

MainWidget::~MainWidget()
{
}

void MainWidget::slotQuit()
{
	delete AppConf;
	((ZApplication *)qApp)->tryQuit();
}

void MainWidget::runEmulator()
{
//	if (romList->currentItem() < 0) return;
//
	RomFileInfo = new QFileInfo(RomPath + "/" + romBox->currentText());
	if ( !RomFileInfo->isFile() || !RomFileInfo->isReadable() ) {
		delete RomFileInfo;
		// Load ROM Error!
		return;
	}
//((ZApplication *)qApp)->tryQuit();

//
	QString ext(RomFileInfo->filePath().right(4).lower());
	QString romfn(RomFileInfo->filePath());
        wgMain->setFullScreenMode(TRUE,FALSE);
        zsv->hide();
	run_smd_emulator( RomFileInfo->filePath().local8Bit(), ext == ".zip" );
	delete RomFileInfo;
	RomFileInfo = 0;
//        wgMain->show();
        wgMain->setFullScreenMode(FALSE,FALSE);
        wgMain->repaint();
        zsv->repaint();
        zsv->show();
        app->showMainWidget(wgMain);
        qApp->quit();
}

void MainWidget::menuSelect(int param)
{
	if (param == mid_about) {
		QString info("<b>EZX PicoDrive</b><br>ver: 1.9");
		info += "<br>2007.04.17";
		info += "<br>Credits to Notaz and Dave";
		info += "<br><br>Port by OopsWare";
                ZNoticeDlg *znd;
                znd = new ZNoticeDlg(ZNoticeDlg::Information, 5000, QString("About"), info, this, "z", true, 0);
//		ZMessageBox::information( this, NULL, info, QString(tr("OK")) );
	}
}

/*
 * application main()
 */

bool fixPath(const QString &s){

	QFileInfo fi(s);

	if ( !fi.exists() ) {
                if ( mkdir( QFile::encodeName( fi.filePath() ), 0777 ) != 0 ) {
                    qWarning("Can't create this dir");
                    return false;
                }
	} else
	if ( !fi.isDir() ) {
            qWarning("This is not directory");
            return false;
        }
	return true;

}

int main( int argc, char **argv )
{
	AppConf = new ConfigFile( QString (APP_PATH) + QString (APP_CONF) );

	RomPath = QString (APP_PATH) + AppConf->readString("ROM_PATH");
	SavePath = QString (APP_PATH) + AppConf->readString("SAVE_PATH");
	CapturePath = QString (APP_PATH) + AppConf->readString("CAP_PATH");

        for (int i = 0; i < EZX_KEY_COUNT; i++ ) {
            HKCS[i].key_code = AppConf->readString("KEY_" + QString(HARDKEYS[i])).toInt();
            HKCS[i].down = false;
        }

	if (!fixPath(RomPath)) {
		delete AppConf;
		return 1;
	}
	if (!fixPath(SavePath)) {
		delete AppConf;
		return 1;
	}
	if (!CapturePath.isEmpty())
		if (!fixPath(CapturePath)) {
			delete AppConf;
			return 1;
		}

    app = new ZApplication(argc, argv);
//    app.enableTouchSound(false);

//    app.enableHardKeyEventFilter(false);

    wgMain = new MainWidget( NULL , NULL ); //QApplication::desktop()
    wgMain->setGeometry(0,0,240,320);
    app->setMainWidget( wgMain );
    wgMain->show();
    return app->exec();
}